package com.jsnkj.basic.wxapi;

import android.app.Activity;
import android.app.Application;
import android.graphics.Bitmap;
import android.os.CountDownTimer;

import com.jsnkj.basic.R;
import com.jsnkj.basic.bean.PayAppUrlEntity;
import com.jsnkj.basic.dialog.LoadingDialog;
import com.jsnkj.basic.util.AppUtil;
import com.jsnkj.basic.util.LogUtils;
import com.jsnkj.basic.util.ToastUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;

/**
 * 微信登录
 */
public class WechatHelper {
    private final IWXAPI mWxApi;
    private CountDownTimer timeOutCountDown;//超时
    private Application mApplication;
    private LoadingDialog mLoadingDialog;
    private OnThirdLoginListener mLoginListener;
    private PayResultListener mPayResultListener;
    private static volatile WechatHelper sInstance;

    public static WechatHelper getInstance(Application application, String wxAppId) {
        if (sInstance == null) {
            synchronized (WechatHelper.class) {
                if (sInstance == null) {
                    sInstance = new WechatHelper(application, wxAppId);
                }
            }
        }
        return sInstance;
    }

    private WechatHelper(Application application, String wxAppId) {
        mWxApi = WXAPIFactory.createWXAPI(application, wxAppId, true);
        mWxApi.registerApp(wxAppId);
        this.mApplication = application;
    }

    /**
     * 获取wxAPI
     */
    public IWXAPI getWxApi() {
        return mWxApi;
    }

    /**
     * 执行微信登录
     */
    public void wechatLogin(Activity activity, OnThirdLoginListener loginListener) {
        if (!AppUtil.isWeixinApplication(mApplication)) {
            ToastUtils.show(R.string.loginlib_wx_uninstalled_hint);
            return;
        }
        mLoadingDialog = new LoadingDialog(activity, null);
        mLoadingDialog.showLoading();

        this.mLoginListener = loginListener;
        new Thread(new Runnable() {
            @Override
            public void run() {
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "diandi_wx_login";
                //像微信发送请求
                mWxApi.sendReq(req);
            }
        }).start();
        if (timeOutCountDown != null) {
            timeOutCountDown.cancel();
        }
        //避免回调一直不执行造成界面卡死 这里加个倒计时
        timeOutCountDown = new CountDownTimer(10 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                mLoadingDialog.hideLoading();
                mLoginListener.onFailed();
            }
        }.start();
    }


    /**
     * 微信支付回调
     */
    public void weChatCallBack(BaseResp baseResp) {
        if(mLoadingDialog!=null){
            mLoadingDialog.hideLoading();
        }
        if (timeOutCountDown != null) {
            timeOutCountDown.cancel();
        }
        LogUtils.e("登录回调：weChatCallBack() getType = " + baseResp.getType());
        switch (baseResp.getType()) {
            case ConstantsAPI.COMMAND_PAY_BY_WX://微信支付
                LogUtils.e("登录回调：微信授权() baseResp.errCode  = " + baseResp.errCode);
                mLoadingDialog.hideLoading();
                if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) { //用户同意
                    if (mPayResultListener != null) {
                        mPayResultListener.onPayResult(true, "支付成功");
                    }
                } else if (baseResp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {//用户取消
                    if (mPayResultListener != null) {
                        mPayResultListener.onPayCancel();
                    }
                } else {
                    if (mPayResultListener != null) {
                        mPayResultListener.onPayResult(false, baseResp.errStr);
                    }
                }
                break;
            case ConstantsAPI.COMMAND_SENDAUTH://微信授权
                //ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4（用户拒绝授权） ERR_USER_CANCEL = -2（用户取消）
                LogUtils.e("登录回调：微信授权() baseResp.errCode  = " + baseResp.errCode);
                if (baseResp.errCode == BaseResp.ErrCode.ERR_OK) {//授权成功
                    SendAuth.Resp resp = (SendAuth.Resp) baseResp;
                    mLoginListener.onSuccess(resp.code);
                } else {//授权失败
                    if (baseResp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
                        mLoginListener.onCancel();
                    } else {
                        mLoginListener.onFailed();
                    }
                }
                break;
            case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX://分享
                break;
            case ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM:
                WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) baseResp;
                if(launchMiniProResp.errCode == 0){
                    mPayResultListener.onPayResult(true,"授权成功");
                }else{
                    mPayResultListener.onPayResult(true,launchMiniProResp.errStr);
                }
        }
    }


    /**
     * 分享网页类型至微信
     *
     * @param webUrl  网页的url
     * @param title   网页标题
     * @param content 网页描述
     * @param bitmap  位图
     */
    public void shareWeb(String webUrl, String title, String content, Bitmap bitmap) {
        // 检查手机或者模拟器是否安装了微信
        if (!getWxApi().isWXAppInstalled()) {
            ToastUtils.show("您还没有安装微信");
            return;
        }

        // 初始化一个WXWebpageObject对象
        WXWebpageObject webpageObject = new WXWebpageObject();
        // 填写网页的url
        webpageObject.webpageUrl = webUrl;

        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage(webpageObject);
        // 填写网页标题、描述、位图
        msg.title = title;
        msg.description = content;
        // 如果没有位图，可以传null，会显示默认的图片
        msg.setThumbImage(bitmap);

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // transaction用于唯一标识一个请求（可自定义）
        req.transaction = "webpage";
        // 上文的WXMediaMessage对象
        req.message = msg;
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        req.scene = SendMessageToWX.Req.WXSceneSession;

        // 向微信发送请求
        getWxApi().sendReq(req);
    }


    /**
     * 分享图片至微信
     *
     * @param bitmap    位图
     * @param shareType 0：分享到好友  1：分享到朋友圈
     */
    public void shareImage(Bitmap bitmap, int shareType) {
        // 检查手机或者模拟器是否安装了微信
        if (!getWxApi().isWXAppInstalled()) {
            ToastUtils.show("您还没有安装微信");
            return;
        }

        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, true);
        bitmap.recycle();
        msg.thumbData = bmpToByteArray(thumbBitmap);  //设置缩略图

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // transaction用于唯一标识一个请求（可自定义）
        req.transaction = "webpage";
        // 上文的WXMediaMessage对象
        req.message = msg;
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈

        if (shareType == 0) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        // 向微信发送请求
        getWxApi().sendReq(req);
    }


    public static byte[] bmpToByteArray(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }


    /**
     * 执行下单操作
     */
    public void PayWXOrder(Activity activity, PayAppUrlEntity entity, PayResultListener payListener) {
        if (!AppUtil.isWeixinApplication(mApplication)) {
            ToastUtils.show(R.string.loginlib_wx_uninstalled_hint);
            return;
        }

        mPayResultListener = payListener;

        mLoadingDialog = new LoadingDialog(activity, null);
        mLoadingDialog.showLoading();
        //微信支付
        PayReq request = new PayReq();//调起微信APP的对象
        request.appId = entity.getAppid();
        request.partnerId = entity.getPartnerid();
        request.prepayId = entity.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = entity.getNoncestr();
        request.timeStamp = entity.getTimestamp();
        request.sign = entity.getSign();
        request.signType = "MD5";


        if (!request.checkArgs()) {
            mLoadingDialog.hideLoading();
            mPayResultListener.onPayResult(false,"支付参数有误");
            return;
        }
        mWxApi.sendReq(request); //发送调起微信的请求

        if (timeOutCountDown != null) {
            timeOutCountDown.cancel();
        }
        //避免回调一直不执行造成界面卡死 这里加个倒计时
        timeOutCountDown = new CountDownTimer(10 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                mLoadingDialog.hideLoading();
                mPayResultListener.onPayCancel();
            }
        }.start();
    }

    public void launchMiniProgram(String ghId,String path, PayResultListener payListener){
        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = ghId; // 填小程序原始id
        req.path = path;                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
        getWxApi().sendReq(req);

        mPayResultListener = payListener;
    }


}